package com.example.springboot.dataSync.service;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.example.springboot.entity.User;
import com.example.springboot.service.ESService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DataSyncService {
    @Autowired
    private ESService esService;

    public void processorUserSyncToElasticSearchAndRedis(CanalEntry.RowChange rowChange, CanalEntry.EventType eventType) throws IOException {
        for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
            if (eventType == CanalEntry.EventType.DELETE) {
                //处理删除数据rowData.getBeforeColumnsList()
                String id = rowData.getBeforeColumnsList().get(0).getValue();
                syncUserDataToElasticSearch(id);
            } else if (eventType == CanalEntry.EventType.INSERT) {
                //处理新增数据rowData.getAfterColumnsList()
                User user = createUserFromColumns(rowData.getAfterColumnsList());
                syncUserDataToElasticSearch(user);
            } else {
                //处理数据修改之后rowData.getAfterColumnsList()
                Map<String, Object> map = new HashMap<>();
                map.put("id", rowData.getAfterColumnsList().get(0).getValue());
                for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
                    if (column.getUpdated()) {
                        map.put(column.getName(), StringEscapeUtils.escapeJava(column.getValue()));
                    }
                }
                if (map.get("update_time") != null) {
                    Object updateTime = map.get("update_time");
                    try {
                        String formattedDate = "";
                        if (updateTime instanceof Date) {
                            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                            formattedDate = outputFormat.format((Date) updateTime);
                        } else if (updateTime instanceof String) {
                            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                            java.util.Date date = inputFormat.parse((String) updateTime);
                            formattedDate = outputFormat.format(date);
                        }
                        map.put("update_time", formattedDate);
                    } catch (Exception e) {
                        // 处理解析错误，如记录日志或抛出异常
                        System.err.println("Failed to parse date: " + updateTime + " Error: " + e.getMessage());
                        throw new IOException("Failed to parse date", e);
                    }
                }
                syncUserDataToElasticSearch(map);
            }
        }
    }

    private void syncUserDataToElasticSearch(User user) throws IOException {
        esService.insertUser(user);
    }

    public void syncUserDataToElasticSearch(String id) throws IOException {
        esService.deleteUser(id);
    }

    public void syncUserDataToElasticSearch(Map<String, Object> map) throws IOException {
        esService.updateUser(map);
    }

    private User createUserFromColumns(List<CanalEntry.Column> columns) {
        User user = new User();
        for (CanalEntry.Column column : columns) {
            System.out.println(column.getValue());
            switch (column.getName()) {
                case "id":
                    user.setId(Integer.valueOf(column.getValue()));
                    break;
                case "username":
                    user.setUsername(column.getValue());
                    break;
                case "nickname":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty()) {
                        user.setNickname(column.getValue());
                    }
                    break;
                case "email":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty()) {
                        user.setEmail(column.getValue());
                    }
                    break;
                case "phone":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setPhone(column.getValue());
                    break;
                case "create_time":
                    Timestamp temp1 = Timestamp.valueOf(column.getValue());
                    user.setCreateTime(new Date(temp1.getTime()));
                    break;
                case "update_time":
                    Timestamp temp2 = Timestamp.valueOf(column.getValue());
                    user.setUpdateTime(new Date(temp2.getTime()));
                    break;
                case "avatar":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setAvatar(column.getValue());
                    break;
                case "all_views":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setAllViews(Integer.valueOf(column.getValue()));
                    break;
                case "article_num":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setArticleNum(Integer.valueOf(column.getValue()));
                    break;
                case "fens_num":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setFensNum(Integer.valueOf(column.getValue()));
                    break;
                case "ip_address":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setIpAddress(column.getValue());
                    break;
                case "signature":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setSignature(column.getValue());
                    break;
                case "birthday":
                    if (column.getValue() != null  && !column.getValue().trim().isEmpty())
                        user.setBirthday(column.getValue());
                    break;
                default:
                    break;
            }
        }
        return user;
    }

}
